import axios, { AxiosRequestConfig, AxiosResponse, Canceler } from 'axios';
import { ElMessage } from 'element-plus';

// 创建axios实例
const http = axios.create({
  baseURL: '/api',
  timeout: 10000,
});

// 撤销请求管理
const pendingRequests = new Map<string, { cancel: Canceler }>();

function getRequestKey(config: AxiosRequestConfig): string {
  return [
    config.method,
    config.url,
    JSON.stringify(config.params),
    JSON.stringify(config.data),
  ].join('&');
}

// 防抖错误提示
let lastErrorTime = 0;
let errorTimer: number | null = null;
const ERROR_DEBOUNCE_MS = 1000; // 1秒内只提示一次

function showErrorOnce(message: string) {
  const now = Date.now();
  if (now - lastErrorTime > ERROR_DEBOUNCE_MS) {
    ElMessage.error(message);
    lastErrorTime = now;
    if (errorTimer) {
      clearTimeout(errorTimer);
      errorTimer = null;
    }
  } else if (!errorTimer) {
    // 延迟最后一次提示
    errorTimer = window.setTimeout(() => {
      ElMessage.error(message);
      lastErrorTime = Date.now();
      errorTimer = null;
    }, ERROR_DEBOUNCE_MS - (now - lastErrorTime));
  }
}

// 请求拦截
http.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 添加token到请求头
    const token = localStorage.getItem('token');
    if (token && config.headers) {
      (config.headers as Record<string, string>).Authorization = `Bearer ${token}`;
    }
    // 撤销重复请求
    const key = getRequestKey(config);
    if (pendingRequests.has(key)) {
      pendingRequests.get(key)?.cancel('请求已撤销');
    }
    config.cancelToken = new axios.CancelToken((cancel) => {
      pendingRequests.set(key, { cancel });
    });
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截
http.interceptors.response.use(
  (response: AxiosResponse) => {
    const key = getRequestKey(response.config);
    pendingRequests.delete(key);
    if (response.data && response.data.code && response.data.code !== 0) {
      // showErrorOnce(response.data.message || '业务错误');
      return Promise.reject(response.data);
    }
    return response.data;
  },
  (error) => {
    if (axios.isCancel(error)) {
      return Promise.reject(error);
    }
    // showErrorOnce(error.response?.data?.message || error.message || '请求失败');
    if (error.config) {
      const key = getRequestKey(error.config);
      pendingRequests.delete(key);
    }
    return Promise.reject(error);
  }
);

// 撤销全部请求
export function cancelAllRequests() {
  for (const { cancel } of pendingRequests.values()) {
    cancel('手动撤销');
  }
  pendingRequests.clear();
}

export default http;